import React, { createContext, useEffect, useReducer, useState } from 'react';
import store from "store";
import { S_MAN_THEME } from "../utils/constant";
import { Switch } from "antd";

export const ThemeContext = createContext({});

export interface ThemeContextProp {
  theme: string;
  lightColor: string;
  darkColor: string;
  toLight: () => void;
  toDark: () => void;
}

const ThemeReducer = (state: object, action: {
  type: string;
  data: any;
}) => {
  switch(action.type) {
    case "SET_THEME":
      store.set(S_MAN_THEME, (action.data).theme)
      return {
        ...state,
        ...action.data
      }
  }
  return state;
}

export const ThemeProvider = (props: any) => {
  const [themeCtx, dispatcher] = useReducer(ThemeReducer, {
    theme: store.get(S_MAN_THEME) || 'light'
  });

  function toLight() {
    dispatcher({
      type: 'SET_THEME',
      data: {
        theme: 'light'
      }
    })
  }

  function toDark() {
    dispatcher({
      type: 'SET_THEME',
      data: {
        theme: 'dark'
      }
    })
  }

  const darkColor = '#001529';
  const lightColor = '#ffffff';
  const color = (themeCtx as any).theme === 'light'
    ? lightColor
    : darkColor

  const renderSwitch = () => {
    return (
      <Switch
        checkedChildren="Light"
        unCheckedChildren="Dark"
        defaultChecked={themeCtx.theme === "light"} onClick={(checked => {
        if (checked) {
          toLight()
        } else {
          toDark()
        }
      })}/>
    )
  }

  return (
    <ThemeContext.Provider
      value={{
        ...themeCtx,
        darkColor,
        lightColor,
        color,
        renderSwitch,
        toLight,
        toDark
      }}>
      {props.children}
    </ThemeContext.Provider>
  )
}